package utils

import (
	"fmt"
	"net/smtp"
	"strconv"
	"strings"
)

type MailConfig struct {
	Host     string
	Port     int
	Username string
	Password string
}

type MailHelper struct {
	mailConfig MailConfig
}

func NewMailHelper(host string, port int, username, password string) *MailHelper {
	return &MailHelper{
		mailConfig: MailConfig{
			Host:     host,
			Port:     port,
			Username: username,
			Password: password,
		},
	}
}

func (mh *MailHelper) SendMail(from, to, subject, msg string, ishtml bool) error {
	config := mh.mailConfig
	auth := smtp.PlainAuth("", config.Username, config.Password, config.Host)

	var content_type string
	if ishtml {
		content_type = "text/html; charset=UTF-8\r\nMIME-Version: 1.0\r\n"
	} else {
		content_type = "text/plain; charset=UTF-8"
	}

	message := fmt.Sprintf("To: %s\r\nFrom: %s <%s>\r\nSubject: %s\r\nContent-Type: %s\r\n\r\n%s",
		to,
		from,
		config.Username,
		subject,
		content_type,
		msg,
	)
	addr := config.Host + ":" + strconv.Itoa(config.Port)
	tos := strings.Split(to, ",")

	err := smtp.SendMail(addr, auth, config.Username, tos, []byte(message))

	return err

}
